import React from "react";
import ReactDOM from "react-dom";
import classnames from "classnames";
import "./index.less";
import { DialogPropsType } from "./PropsType";
import Modal from "rmc-dialog";
const Dialog = (props: DialogPropsType) => {
  const {
    title,
    message,
    cancelText = "取消",
    confirmText = "确定",
    onCancel = () => {},
    onConfirm = () => {},
  } = props;
  // const cls = classnames("m-react-dialog");
  let closed = false;
  const prefix = "m-react-dialog"; //前缀
  if (!title) {
    //如果未传入标题，则返回一个空的close
    return {
      close: () => {},
    };
  }

  //函数式Portals
  const div = document.createElement("div");
  document.body.appendChild(div);

  //组件卸载
  function close() {
    ReactDOM.unmountComponentAtNode(div);
    if (div?.parentNode) {
      div.parentNode.removeChild(div);
    }
  }

  // 事件支持同步事件和异步事件
  function handlePress(type: "cancel" | "confirm") {
    const actionMap = {
      cancel: onCancel,
      confirm: onConfirm,
    };
    const action = actionMap[type];
    if (closed) {
      return;
    }
    if (action?.then) {
      action
        .then(() => {
          closed = true;
          close();
        })
        .catch(() => {});
    } else {
      action();
      closed = true;
      close();
    }
  }
  ReactDOM.render(
    <Modal closable={false} visible wrapClassName={prefix} animation="zoom">
      <div className={`${prefix}-body`}>
        <div
          className={classnames(`${prefix}-title`, { withMessage: !!message })}
        >
          {title}
        </div>
        {message && <div className={`${prefix}-message`}>{message}</div>}
        <div className={`${prefix}-btn-group`}>
          <div
            className={`${prefix}-btn-cancel`}
            onClick={() => handlePress("cancel")}
          >
            {cancelText}
          </div>
          <div
            className={`${prefix}-btn-confirm`}
            onClick={() => handlePress("confirm")}
          >
            {confirmText}
          </div>
        </div>
      </div>
    </Modal>,
    div
  );
  return { close };
};

export default Dialog;
